#include "common.h"
#include "utils.h"
#include "strutils.h"
#include "strlist.h"

int encodeReq(PReq req, char *target)
{
	int ret=sprintf(target, 
		"ReqID=%d\nURL=%s\nCT=%s\nCookies=%s\nMethod=%s\nCL=%d\n",
		req->ReqID, req->URL, req->ContentType, req->Cookies, req->Method, req->ContentSize);
	if(req->Content)
	{
		ret+=sprintf(target+ret, "Content=");
		ret+=encodeLine(target+ret, req->Content);
	}
	return ret;
}

int decodeReq(const char *reqStr, char *content, PReq req)
{
	PStrList reqList=slCreate("");
	char *p;
	memset(req, 0, sizeof(TReq));
	slSetText(reqList, reqStr, "\n");
//	logMsg("ReqLine Count=%d,",reqList->count);
//	logMsg("'ReqID',");
	req->ReqID=slGetValueInt(reqList, "ReqID", -1);
	p=slGetValue(reqList, "URL");
	if(p) strcpy(req->URL, p);
	p=slGetValue(reqList, "CT");
	if(p) strcpy(req->ContentType, p);
	p=slGetValue(reqList, "Cookies");
	if(p) decodeLine(p, req->Cookies);
	req->Content=slGetValue(reqList, "Content");
	p=slGetValue(reqList, "CL");
	if(p) req->ContentSize=atoi(p);
	if(req->Content)
	{
		if(content==NULL)
			content=(char *)reqStr;
		req->ContentSize=decodeLine(req->Content, content);
		req->Content=content;
//		logMsg("%d bytes. Finish.\n", req->ContentSize);
	}
	slFree(reqList);
	return 1;
}

PStrList queryStrToList(const char *queryStr)
{
	PStrList res=slCreate("");
	if(queryStr)
	{
		int i;
		PStrList content=slCreate("");
		slSetText(content, queryStr, "&");
		for(i=0;i<content->count;i++)
		if(content->strs[i])
			slAdd(res, decodeQueryStr(content->strs[i]));
		slFree(content);
	}
	return res;
}


